#include "stdafx.h"
#include "LogManager.h"
#include "Logger.h"

LogManagement::LogManagement()
{
	
	m_LoggerList.push_back(new OSLogger());

	m_ConsoleLogger = new ConsoleLogger;
	m_LoggerList.push_back(m_ConsoleLogger);

	m_LogInputHandler = new LogInputHandler(this);

	LogManager::getSingleton().getDefaultLog()->addListener(this);
}

LogManagement::~LogManagement()
{
	LogManager::getSingleton().getDefaultLog()->removeListener(this);

	SAFE_DELETE(m_LogInputHandler);

	for (uint i = 0; i < m_LoggerList.size(); ++i)
		delete m_LoggerList[i];

	m_LoggerList.clear();
	m_Filters.clear();

	m_ConsoleLogger = NULL;
}

bool LogManagement::AddFilter(const char* str, uint len)
{
	if (len < 2) return false;
	if (IsFilter(str, len)) return true;

	u16 h = str[0] | (str[1] << 8);
	m_Filters.push_back(h);

	return true;
}

bool LogManagement::DelFilter( const char* str, uint len )
{
	if (len < 2) return false;
	u16 h = str[0] | (str[1] << 8);
	m_Filters.erase(std::remove(m_Filters.begin(), m_Filters.end(), h));

	return true;
}

void LogManagement::ClearFilter()
{
	m_Filters.clear();
}

bool LogManagement::IsFilter( const char* str, uint len )
{
	if (len < 2) return false;
	
	std::vector<u16>::iterator result;
	u16 h = str[0] | (str[1] << 8);
	result = std::find(m_Filters.begin(), m_Filters.end(), h);
	
	if (result != m_Filters.end())
		return true;

	return false;
}

void LogManagement::Write( const char* fmt, ... )
{
	for (size_t i = 0; i < m_LoggerList.size(); ++i)
	{
		if (!m_LoggerList[i]->IsActivate())
			continue;

		va_list args;
		va_start(args, fmt);
		m_LoggerList[i]->Write(fmt, args);
		va_end(args);
	}
}

void LogManagement::messageLogged(const String& message, LogMessageLevel lml, 
									bool maskDebug, const String &logName)
{
//	Write(message.c_str());
}

void LogManagement::UpdateKey(InputKeyEvent* evt)
{
	for (size_t i = 0; i < m_LoggerList.size(); ++i)
	{
		if (m_LoggerList[i]->IsInputUpdate())
			m_LoggerList[i]->InputUpdate(evt);
	}
}

void LogManagement::LogInit()
{
	if (m_ConsoleLogger)
		m_ConsoleLogger->Init();

	g_InputService->GetInputChannel()->AddHandler(m_LogInputHandler);
}

void LogManagement::LogShutdown()
{
	if (m_ConsoleLogger)
		m_ConsoleLogger->Shutdown();
}

bool LogManagement::IsConsoleVisible()
{
	return m_ConsoleLogger->IsVisible();
}

void LogManagement::SetConsoleVisible(bool visible)
{
	m_ConsoleLogger->SetVisible(visible);
}

void LogManagement::ConsoleUpdate(FrameUpdatedEvent* evt)
{
	m_ConsoleLogger->ConsoleUpdate(evt);
}
//////////////////////////////////////////////////////////////////////////

LogInputHandler::LogInputHandler(LogManagement* manager)
:m_logManager(manager)
{
}

void LogInputHandler::OnEvent(Event* evt)
{
	BEGIN_EVENT_HANDLER(evt);

	ON_EVENT(InputKeyEvent)
	{
		m_logManager->UpdateKey(evt);
	}

	END_EVENT_HANDLER;
}